<?php
namespace app\backend\model;

use think\Model;

class Member extends Model
{

    // 设置完整的数据表（包含前缀）
    protected $memberTable = 'z_member';
    protected $moneyTable = 'z_member_money';
    protected $loginTable = 'z_tp_login_log';
    protected $relationTable = 'z_relation';
    protected $journalTable = 'z_member_journal';
    protected $payBillTable = 'z_pay_bill';
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取全部会员数据
     * @date   2016-12-29
     * @author Lanlc
     *
     * @param  int    $page    页数
     * @param  int    $pageSize  数量
     * @param  array  $where     查询条件
     *
     * @return
     */
    public function getMembers($page, $pageSize, $where)
    {
        $field = 'm.id,dtype,username,mobile,status,sex,nickname,n.money';
        $res =   $this->setTable($this->memberTable. ' m')
                ->join($this->moneyTable. ' n', 'm.id=n.mid', 'LEFT')
                ->field($field)
                ->where($where)
                ->order('id', 'ASC')
                ->page($page, $pageSize)
                ->select();
        if (!$res) {
            return [];
        }

        $sum = $this->setTable($this->memberTable. ' m')
            ->join($this->moneyTable. ' n', 'm.id=n.mid', 'LEFT')
            ->where($where)
            ->count();
        $data = [
            'page'  => $page,
            'total' => ceil($sum / $pageSize),
            'list'  => $res
        ];
        return $data;
    }

    /**
     * 增加会员
     * @date   2016-12-29
     * @author Lanlc
     *
     *
     * @return
     */
    public function addMember($data)
    {
        $mid =   $this->setTable($this->memberTable)->insertGetId($data);
        return $mid;
    }



    public function updateUser($mid, $data)
    {
        return $this->setTable($this->memberTable)->where(['id' => $mid])->update($data);
    }

    /**
     * 添加运营方和业主关系
     * @date   2016-
     * @author Lanlc
     *
     *
     * @return
     */
    public function addRelation($data)
    {
        return $this->setTable($this->relationTable)->insertGetId($data);
    }

    /**
     * 获取当前用户添加的全部会员数据
     * @date   2016-12-29
     * @author Lanlc
     *
     * @param  int    $offSet    偏移量
     * @param  int    $pageSize  数量
     * @param  array  $where     查询条件
     *
     * @return
     */
    public function getOwnerMembers($page, $pageSize, $where)
    {
        $field = 'm.id,dtype,username,mobile,m.status as m_status,sex,nickname,n.money';
        $res =   $this->setTable($this->relationTable. ' r')->join($this->memberTable. ' m', 'm.id=r.son_id', 'LEFT')->join($this->moneyTable. ' n', 'm.id=n.mid', 'LEFT')
            ->field($field)->where($where)->order('id', 'ASC')->page($page, $pageSize)->select();
        if (!$res) {
            return [];
        }

        $sum = $this->setTable($this->relationTable. ' r')
            ->join($this->memberTable. ' m', 'm.id=r.son_id', 'LEFT')
            ->join($this->moneyTable. ' n', 'm.id=n.mid', 'LEFT')
            ->where($where)
            ->count();
        $data = [
            'page'  => $page,
            'total' => ceil($sum / $pageSize),
            'list'  => $res
        ];
        return $data;
    }

    /**
     * 获取会员信息
     * @date   2016-1-9
     * @author Lanlc
     *
     * @param  array   $where  查询条件
     * @param  string  $field  查询字段
     *
     * @return
     */
    public function getMemberInfo($where, $field)
    {
        return $this->setTable($this->memberTable)->field($field)->where($where)->select();
    }

    /**
     * 根据手机号获取用户信息
     * @param $mobile
     * @param string $field
     * @return mixed
     */
    public function getMemberInfoByMobile($mobile, $field='*')
    {
        $where = ['mobile' => $mobile];
        return $this->setTable($this->memberTable)->field($field)->where($where)->find();
    }

    /**
     * 获取运营方关联的用户信息
     * @date   2016-01-11
     * @author Lanlc
     *
     * @param  int $type      关联用户类型
     *
     * @return
     */
    public function getOperatorMmeber($type = 1, $field = 'nickname, id')
    {
        return $this->setTable($this->memberTable)->field($field)->where(['dtype' => $type])->select();
    }

    /**
     * 获取会员余额
     * @date   2017-01-20
     * @author Lanlc
     *
     * @param  int  $mid  会员ID
     *
     * @return
     */
    public function getMemberMoney($mid)
    {
        if (!$mid) {
            return false;
        }
        $res = $this->setTable($this->moneyTable)->field('money')->where(['mid' => $mid])->find();
        if ($res) {
            return $res['money'];
        } else {
            return false;
        }
    }

    /**
     * 获取会员冻结金额(先获取租赁账单的，托管账单的先不管)
     * @date   2017-05-10
     * @author wuhao
     *
     * @param  int  $mid  会员ID
     *
     * @return
     */
    public function getFreezeMoney($mid)
    {
        if (!$mid) {
            return false;
        }
        $where = ['tenant_id' => $mid, 'begin_cycle' => ['elt', date('Ymd')], 'is_delete' => 0];
        $field = 'SUM(money) freeze_money';
        $res =  $this->setTable($this->payBillTable)->field($field)->where($where)->group('tenant_id')->find();
        return $res ? $res['freeze_money'] : 0;
    }

    /**
     * 新增会员余额记录
     * @date   2017-01-20
     * @author wuhao
     *
     * @param array $data 要插入的数据
     * @return
     */
    public function addMemberMoney($data)
    {
        return $this->setTable($this->moneyTable)->insertGetId($data);
    }

    /**
     * 修改会员资金
     * @date   2017-01-20
     * @author Lanlc
     *
     * @param  int      $mid           当前对象id
     * @param  int      $ownerId       与之相关的对象id
     * @param  int      $opID          操作员ID
     * @param  int      $money         修改金额
     * @param  int      $action        修改动作，0增加，1减少
     * @param  int      $type          交易类型:交易类型：1余额缴费，2通联支付宝，3通联微信，4提现申请, 5富友B2C 6富友B2B, 7通联代付
     * @param  int      $orderId       订单id
     * @param  string   $orderNum      订单号
     * @param  int      $mtype         缴费类型：1房租，2物业，3水，4电,  5公摊水，6公摊电, 7税费, 8其他费用，9.优惠金额  21租赁账单 22 托管账单，31 实际提现金额 32 提现手续费 41通联代付
     * @param  string   $memo          备注
     * @param  int      $tradeNo       外部流水号
     * @param  int      $beginCycle    账单起始周期
     * @param  int      $endCycle      账单起始周期
     * @param  bool     $useTrans      是否使用事务
     *
     * @return array
     */
    public function modifyMemberMoney($mid, $ownerId, $opID, $money, $action, $type,$orderId, $orderNum, $mtype, $memo='', $tradeNo=0, $beginCycle=0, $endCycle=0, $useTrans = true)
    {
        $act = $action ? '-' : '+';

        if ($useTrans) {
            $this->startTrans();
        }

        $moneyRes = $this->setTable($this->moneyTable)->where(['mid' => $mid])->update(['money' => ['exp', "money{$act}{$money}"]]);
        if (!$moneyRes) {
            if ($useTrans) {
                $this->rollback();
            }
            return ['code'=>401, 'msg'=>'sql:'.$this->getLastSql()];
        }

        $lastMoney = $this->getMemberMoney($mid);
        $journalPlatformModel = new JournalPlatform();
        $journalPlatformModel->setAllProperty($mid, $money, $lastMoney, $orderId, $orderNum, $ownerId, $action, time(), $opID, $type, $memo, $tradeNo, $mtype, $beginCycle, $endCycle);
        $journalRes = $journalPlatformModel->addRecord();
        if ($journalRes === false) {
            if ($useTrans) {
                $this->rollback();
            }
            return ['code'=>401, 'msg'=>'sql:'.$journalPlatformModel->getLastSql()];
        }
        if ($useTrans) {
            $this->commit();
        }
        return ['code'=>200, 'msg'=>'ok'];
    }


    /**
     * @comment 更新冻结余额
     * @author wuhao
     * @param $memberId 用户id
     * @param $action   0=增加 1=减少
     * @param $money    金额 分
     * @return mixed
     */
    public function updateFreezeMoney($memberId, $action, $money)
    {
        $act = $action ? '-' : '+';
        $moneyRes = $this->setTable($this->moneyTable)->where(['mid' => $memberId])->update(['freeze_money' => ['exp', "freeze_money{$act}{$money}"]]);
        return $moneyRes;
    }

    /**
     * 提现申请金额的修改
     * @date   2017-05-11
     * @author wuhao
     *
     * @param  int      $mid           提现人id
     * @param  int      $admin         平台admin账号id
     * @param  int      $actualMoney   实际提现金额
     * @param  int      $serviceMoney  手续费
     * @param  int      $orderId       订单id
     * @param  int      $orderNum      订单号
     * @param  int      $money         提现金额
     * @param  string   $bankName      银行名称
     * @param  string   $account       账号
     *
     * @return array
     */
    public function withdrawMoneyModify($mid, $admin, $actualMoney, $serviceMoney, $orderId, $orderNum, $money, $account, $bankName)
    {
        $moneyYuan        = yuan($money);
        $actualMoneyYuan  = yuan($actualMoney);
        $serviceMoneyYuan = yuan($serviceMoney);

        $memo = "申请提现金额:{$moneyYuan}元,手续费:{$serviceMoneyYuan}元,实际提现金额:{$actualMoneyYuan}元";
        $memo .= "【{$account}({$bankName})】";

        $resAct = $this->modifyMemberMoney($mid, $mid, $mid, $actualMoney, 1, 4, $orderId,  $orderNum, 10, $memo, 0, 0, 0, false);//账户余额扣除实际提现金额
        if ($resAct['code'] != 200) {
            return ['code' => $resAct['code'], 'msg' => $resAct['msg']];
        }

        $memoFee = "提现手续费为:{$serviceMoneyYuan}元";
        $resFee = $this->modifyMemberMoney($mid, $admin, $mid, $serviceMoney, 1, 4,$orderId,  $orderNum, 11, $memoFee, 0, 0, 0, false);//账户余额扣除手续费
        if ($resFee['code'] != 200) {
            return ['code' => $resFee['code'], 'msg' => $resFee['msg']];
        }

        $adminFee = $this->modifyMemberMoney($admin, $mid, $admin, $serviceMoney, 0, 4,$orderId,  $orderNum, 11, $memoFee, 0, 0, 0, false);//ADMIN账户新增手续费
        if ($adminFee['code'] != 200) {
            return ['code' => $adminFee['code'], 'msg' => $adminFee['msg']];
        }
        return ['code' => 200, 'msg' =>'ok'];
    }
    /**
     * 根据收费对象id 获取收费对象类型
     * @date   2016-01-23
     * @author banjin
     * @param  $id  int|array  用户id
     *
     * @return bool|array
     */
    public function getMemberTypd($id)
    {
        if (!$id) {
            return false;
        }
        $this->table($this->memberTable)->field('id, dtype');
        if (is_array($id)) {
            $where = ['id' => ['in', $id]];
            $res   = $this->where($where)->select();
        } else {
            $where = ['id' => $id];
            $res   = $this->where($where)->find();
        }
        return $res ?: [];
    }

    /**
     * 根据id获取用户的名称和电话
     * @date   2017-04-21
     * @author wuhao
     * @param   int|array $id  用户id
     *
     * @return array
     */
    public function getMemberName($id)
    {
        if (!$id || (!is_array($id) && !is_numeric($id))) {
            return false;
        }
        $this->table($this->memberTable)->field('id, nickname, mobile');
        if (is_array($id)) {
            $where = ['id' => ['in', $id]];
            $res   = $this->where($where)->select();
        } else {
            $where = ['id' => $id];
            $res   = $this->where($where)->find();
        }
        return $res ?: [];
    }

    /**
     * 检测登录密码是否正确
     * @date   2017-05-03
     * @author wuhao
     * @param   int     $mid      用户id
     * @param   string  $password 旧密码
     *
     * @return bool
     */
    public function checkOldPassword($mid, $password)
    {
        if (!$mid || !$password) {
            return false;
        }
        $old = $this->setTable($this->memberTable)->where(['id' => $mid])->value('password');
        return $password == $old;
    }

    /**
     * 重置用户密码
     * @date   2017-05-03
     * @author wuhao
     * @param  int    $mid          用户id
     * @param  string $newPassword  新密码
     *
     * @return bool
     */
    public function resetPassword($mid, $newPassword)
    {
        if (!$mid || !$newPassword) {
            return false;
        }
        $data = [
            'password' => md5(md5($newPassword)),
            'update_time' => time(),
        ];
        $res = $this->setTable($this->memberTable)->where(['id' => $mid])->update($data);
        return $res ? true : false;
    }

    /**
     * 重置用户密码
     * @date   2017-05-03
     * @author wuhao
     * @param  int    $mobile       手机号
     * @param  string $newPassword  新密码
     *
     * @return bool
     */
    public function resetPasswordByMobile($mobile, $newPassword)
    {
        if (!$mobile || !$newPassword) {
            return false;
        }
        $data = [
            'password' => md5(md5($newPassword)),
            'update_time' => time(),
        ];
        $res = $this->setTable($this->memberTable)->where(['mobile' => $mobile])->update($data);
        return $res ? true : false;
    }

    /**
     * 根据用户id获取用户信息
     * @date   2017-05-04
     * @author wuhao
     * @param  int|array    $mid      用户id
     * @param  string $field    获取字段
     *
     * @return array
     */
    public function getMemberInfoById($mid, $field = '*')
    {
        if (!$mid || !$field || (!is_array($mid) && !is_numeric($mid))) {
            return false;
        }
        $this->setTable($this->memberTable)->field($field);
        if (is_numeric($mid)) {
            $res = $this->where(['id' => $mid])->find();
        } else {
            $res = $this->where(['id' => ['in', $mid]])->select();
        }
        return $res ?: [];
    }

    /**
     * 根据用户账号获取用户信息
     * @date   2017-05-04
     * @author wuhao
     * @param  int|array    $account  用户账号
     * @param  string       $field    获取字段
     *
     * @return bool
     */
    public function getMemberInfoByAccount($account, $field = '*')
    {
        if (!$account || !$field) {
            return false;
        }
        $this->setTable($this->memberTable)->field($field);
        if (is_array($account)) {
            $res = $this->where(['username' => ['in', $account], 'status' => 1])->select();
        } else {
            $res = $this->where(['username' =>  $account, 'status' => 1])->find();
        }
        return $res ?: [];
    }

    /**
     * 租赁签约模糊查询租户姓名返回租户基本信息
     * @date   2017-05-16
     * @author wuhao
     *
     * @param  string  $name   租户姓名
     *
     * @return array
     */
    public function searchTenant($name)
    {
        $where['dtype'] = 2;
        if ($name) {
            $where['nickname'] = ['like', "%$name%"];
        }
        $field = 'id, nickname';
        return $this->setTable($this->memberTable)->field($field)->where($where)->limit(0, 30)->select();
    }

    /**
     * 租赁签约查询租户
     * @date   2017-05-16
     * @author wuhao
     *
     * @param  int  $id   租户id
     *
     * @return array
     */
    public function searchTenantById($id)
    {
        if (!$id) {
            return false;
        }
        $where = [
            'id' => $id,
            'dtype' => 2,
        ];
        $field = 'id, user_type, nickname, sex, id_card, mobile, address, license';
        return $this->setTable($this->memberTable)->field($field)->where($where)->find();
    }

    /**
     * 查询员工的父账号id
     * @param $mid 员工id
     * @return array
     */
    public function getParentId($mid)
    {
        if (!$mid) {
            return false;
        }
        $where = [
            'son_id' => $mid,
            'son_id_type' => 1,
        ];
        $field = 'parent_id';
        return $this->table($this->relationTable)->field($field)->where($where)->find();
    }

    /**
     * @comment 查询员工列表
     * @author wuhao
     * @param int     $memberId 父账号id
     * @param string  $query    查询条件
     * @param int  $page 页数
     * @param int  $pageSize  每页个数
     * @return mix
     */
    public function getEmployee($memberId, $query, $page = 1, $pageSize = 15)
    {
        if (!$memberId || $page<=0 || $pageSize<=0) {
            return false;
        }
        $where = 'r.son_id_type = 1 AND r.parent_id = ' . $memberId . ' ';
        if ($query) {
            $where .= 'AND (m.mobile = "'. $query.'" OR m.nickname like ' . "\"%$query%\")";
        }

        $field = 'm.id, m.mobile, m.nickname, m.status, m.username';
        $res =  $this->table($this->memberTable . ' m')
            ->field($field)
            ->join($this->relationTable. ' r', 'm.id=r.son_id', 'LEFT')
            ->where($where)
            ->page($page, $pageSize)
            ->select();
        if (!$res) {
            $data = [];
        } else {
            $sum = $this->table($this->memberTable . ' m')
                ->field($field)
                ->join($this->relationTable. ' r', 'm.id=r.son_id', 'LEFT')
                ->where($where)
                ->count();
            $total = ceil($sum / $pageSize);
            $data = [
                'total' => $total,
                'list'  => $res,
            ];
        }
        return $data;
    }
}
